<template>
  <div class="mod_box">
    <modTabs :tabIndex="tabIndex"></modTabs>
    <el-row>
      <el-col style="text-align: center;">
        <el-input
          v-model.trim="deptName"
          placeholder="输入名称"
          :style="'width:50%;margin:5px 0px;'"
          @keyup.enter.native="search"
        >
          <el-button slot="append" @click="search">搜索</el-button>
        </el-input>
      </el-col>
    </el-row>

    <el-row class="mod_title">
      <el-col :sm="4">
        <div class="g-title">内设机构数（{{total}}个）</div>
      </el-col>
      <el-col :sm="20" style="text-align: right;">
        <el-button type="primary" v-if="admintype==3" @click="add" size="small">新增</el-button>
        <el-button type="success" v-if="admintype==3" @click="edit" size="small">修改</el-button>
        <el-button type="danger" v-if="admintype==3" @click="del" size="small">删除</el-button>
      </el-col>
    </el-row>

    <el-table
      class="mod_table"
      ref="multipleTable"
      :data="listData"
      tooltip-effect="dark"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column type="index" label="序号" width="55" align="center"></el-table-column>
      <el-table-column prop="deptName" label="机构名称" align="center"></el-table-column>
      <el-table-column prop="userCount" label="部门人数" width="120" align="center"></el-table-column>
      <el-table-column label="人员列表" width="120" show-overflow-tooltip align="center">
        <template slot-scope="scope">
          <el-button @click="showUser(scope.row.id)" type="text">点击查看</el-button>
        </template>
      </el-table-column>
      <el-table-column
        prop="showOrder"
        label="自定义顺序"
        show-overflow-tooltip
        align="center"
        width="120"
      >
        <template slot-scope="scope">
          <el-input
            @input="((val)=>{changeStatus(val, scope.row.id)})"
            v-model="scope.row.showOrder"
            type="number"
          ></el-input>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120" show-overflow-tooltip align="center">
        <template slot-scope="scope">
          <el-button @click="(addUser(scope.row.id))" type="success">添加人员</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-row style="padding: 32px 16px;">
      <el-col>
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :page-size="pageSize"
          :total="total"
          :current-page="pageNo"
          @current-change="fetchData"
          @size-change="pageSizeChange"
        ></el-pagination>
      </el-col>
    </el-row>

    <el-dialog
      title="新增机构"
      ref="tableDialog"
      :visible.sync="dialogVisible"
      border
      width="80%"
      v-if="formData"
    >
      <el-form :model="formData" label-width="100px" :rules="formRules" ref="form">
        <el-row>
          <el-col :sm="24">
            <el-form-item label="机构名称" prop="deptName">
              <el-input v-model="formData.deptName" placeholder="请输入机构名称"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer" style="text-align: left;">
        <el-button type="primary" @click="save">保存数据</el-button>
        <el-button @click="resetForm">重置表单</el-button>
      </span>
    </el-dialog>

    <el-dialog title="人员信息" ref="tableDialog" :visible.sync="UserShow" width="80%" v-if="UserShow">
      <el-table
        ref="multipleTable"
        :data="listUserData"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column type="index" label="序号"></el-table-column>
        <el-table-column prop="loginname" label="登录账号" align="center"></el-table-column>
        <el-table-column prop="username" label="姓名" align="center"></el-table-column>
        <el-table-column prop="mobile" label="手机" align="center"></el-table-column>
        <el-table-column prop="phone" label="座机" align="center"></el-table-column>
        <el-table-column prop="zw" label="职务" align="center"></el-table-column>
        <el-table-column prop="registtime" label="创建时间" align="center"></el-table-column>
      </el-table>
      <el-row style="padding: 16px;">
        <el-col>
          <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :page-size="UserpageSize"
            :total="Usertotal"
            :current-page="UserpageNo"
            @current-change="UserfetchData"
            @size-change="UserpageSizeChange"
          ></el-pagination>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer" style="text-align: left;">
        <el-button v-if="addUserMode" type="primary" @click="saveUser">添加人员</el-button>
        <el-button v-if="!addUserMode" type="danger" @click="saveUser">移除人员</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.mod_box {
  padding: 20px;
}
.mod_title {
  padding: 20px 0;
  .g-title {
    height: 20px;
    padding-left: 8px;
    line-height: 22px;
    font-size: 16px;
    font-weight: 400;
    border-left: 2px solid #f54e40;
    margin: 10px 0;
    display: inline-block;
  }
}

.mod_table th {
  background-color: #f5f7fa !important;
}

.el-dialog {
  -webkit-transform: none;
  transform: none;
  left: 0;
  position: relative;
  margin: 0 auto;
  background: #eef1f6;
  .el-dialog__body {
    background-color: #fff;
    margin: 0px 10px;
  }
}
</style>
<script>
import { axios } from "@/api/axios";
import modTabs from "../../components/modTabs/index";
import { mapGetters } from "vuex";
export default {
  components: { modTabs },
  data: function () {
    return {
      admintype: 0,
      tabIndex: "0",
      total: 0,
      pageNo: 1,
      pageSize: 10,
      deptName: "",
      dialogVisible: false, //新增机构
      addMode: false, //机构新增or编辑
      formData: null,
      formRules: {
        deptName: [
          {
            required: true,
            message: "请输入机构名称",
            trigger: "blur",
          },
        ],
      },
      listData: [], //全部数据
      Usertotal: 0,
      UserpageNo: 1,
      UserpageSize: 10,
      addUserMode: false, //人员新增or编辑
      Userdeptid: "",
      UserShow: false, //人员列表
      listUserData: [], //人员列表
      listDataSelected: [], //选中数据
    };
  },
  created() {
    this.fetchData();
    this.admintype = this.userInfo.usertype;
  },
  computed: {
    ...mapGetters(["userInfo", "selectedComIds"]),
  },
  watch: {
    //监听左侧单位勾选 重新获取数据
    selectedComIds() {
      this.pageNo = 1;
      this.fetchData();
    },
  },
  methods: {
    search() {
      this.pageNo = 1;
      this.fetchData();
    },
    pageSizeChange(newSize) {
      this.pageSize = newSize;
      this.pageNo = 1;
      this.fetchData();
    },
    fetchData(pageNo) {
      if (pageNo) {
        this.pageNo = pageNo;
      }
      axios("/admin/dept/listJson.do", "get", {
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        deptName: this.deptName,
        comIds: this.selectedComIds.join(","),
      }).then((response) => {
        this.listData = response.data;
        this.total = response.total;
        this.listDataSelected.splice(0);
      });
    },
    //表格多选
    handleSelectionChange(val) {
      this.listDataSelected.splice(0);
      val.forEach((e) => {
        this.listDataSelected.push(e);
      });
      console.log(this.listDataSelected);
    },
    resetForm() {
      this.$refs.form.resetFields();
    },
    //检查登录名合法性
    checkName(rule, value, callback) {
      if (!value || !value.trim() || value.length == 0) {
        callback(new Error("请输入登录账户"));
      }
      if (this.addMode == true) {
        var url = "/admin/checkName.do";
        axios(url, "get", {
          name: this.formData.loginname,
        }).then((data) => {
          if (data) {
            callback();
          } else {
            callback(new Error("账户已存在"));
          }
        });
      }
    },
    //新增按钮事件
    add() {
      this.formData = {
        deptName: "",
      };
      this.addMode = true;
      this.dialogVisible = true;
    },
    edit() {
      if (this.listDataSelected.length == 0) {
        this.$message("请选择");
        return;
      }
      var formOld = JSON.parse(JSON.stringify(this.listDataSelected[0]));
      this.formData = {
        deptName: formOld.deptName,
        id: formOld.id,
      };
      this.addMode = false;
      this.dialogVisible = true;
    },
    del() {
      if (this.listDataSelected.length == 0) {
        this.$message("请选择");
        return;
      }
      var formOld = JSON.parse(JSON.stringify(this.listDataSelected));
      var formData = "";
      for (var key in formOld) {
        formData = formData + "," + formOld[key].id;
      }
      var formData = formData.slice(1);
      var formArray = {
        id: formData,
      };
      var param = new URLSearchParams();

      for (var key in formArray) {
        if (formArray[key] instanceof Array) {
          param.append(key, formArray[key].join(","));
        } else {
          param.append(
            key,
            typeof formArray[key] === "undefined" ? "" : formArray[key]
          );
        }
      }
      axios("/admin/dept/removeDept.do", "post", param).then((data) => {
        if (data.error == 0) {
          this.$message("操作成功");
          this.dialogVisible = false;
          this.fetchData();
        } else {
          this.$message("操作失败");
        }
      });
    },
    save() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          var url = "/admin/dept/updateDept.do";
          if (this.addMode) {
            url = "/admin/dept/addDept.do";
          }
          axios(url, "post", this.formData).then((data) => {
            if (data.error == 0) {
              this.$message("操作成功");
              this.dialogVisible = false;
              this.fetchData();
            } else {
              this.$message("操作失败");
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    changeStatus(val1, val2) {
      var formData = JSON.parse(
        JSON.stringify({
          showOrder: val1,
          deptId: val2,
        })
      );
      var param = new URLSearchParams();
      for (var key in formData) {
        if (formData[key] instanceof Array) {
          param.append(key, formData[key].join(","));
        } else {
          param.append(
            key,
            typeof formData[key] === "undefined" ? "" : formData[key]
          );
        }
      }
      var url = "/admin/dept/changeShowOrder.do";
      axios(url, "post", param).then((data) => {
        if (data.error == 0) {
          this.$message("操作成功");
          this.dialogVisible = false;
          this.fetchData();
        } else {
          this.$message("操作失败");
        }
      });
    },
    //增加账号
    addUser(val) {
      this.addUserMode = true;
      this.Userdeptid = val;
      this.UserfetchData();
    },
    showUser(val) {
      this.addUserMode = false;
      this.Userdeptid = val;
      this.UserfetchData();
    },
    saveUser() {
      if (this.listDataSelected.length == 0) {
        this.$message("请选择");
        return;
      }
      var formOld = JSON.parse(JSON.stringify(this.listDataSelected));
      var formData = "";
      for (var key in formOld) {
        formData = formData + "," + formOld[key].userid;
      }
      var formData = formData.slice(1);
      var url = "/admin/user/removeUserFromDept.do";
      var param = {
        ids: formData,
        deptId: this.Userdeptid,
      };
      if (this.addUserMode) {
        url = "/admin/user/changeUserDept.do";
        param = {
          ids: formData,
          deptId: this.Userdeptid,
        };
      }
      axios(url, "post", param).then((data) => {
        if (data.error == 0) {
          this.$message("操作成功");
          this.UserShow = false;
          this.fetchData();
        } else {
          this.$message("操作失败");
        }
      });
    },
    UserfetchData(UserpageNo) {
      if (UserpageNo) {
        this.UserpageNo = UserpageNo;
      }
      var url = "/admin/dept/findUsers.do";
      var param = {
        pageNo: this.UserpageNo,
        pageSize: this.UserpageSize,
        deptId: this.Userdeptid,
      };
      if (this.addUserMode) {
        url = "/admin/user/findUsersByCompanyIdAndDeptId.do";
        param = {
          pageNo: this.UserpageNo,
          pageSize: this.UserpageSize,
          deptId: this.Userdeptid,
          companyId: this.userInfo.comid,
        };
      }
      axios(url, "get", param).then((data) => {
        this.listUserData = data.data;
        this.Usertotal = data.total;
        this.UserShow = true;
      });
    },
    UserpageSizeChange(newSize) {
      this.UserpageSize = newSize;
      this.UserpageNo = 1;
      this.UserfetchData();
    },
  },
};
</script>